package com.example.mybatis.my.shop.controller;

import com.example.mybatis.my.shop.entity.TbUser;
import com.example.mybatis.my.shop.service.TbUserService;
import com.example.mybatis.my.shop.service.impl.TbUserServiceImpl;
import com.example.mybatis.my.shop.utils.CookieUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/login")
public class LoginController extends HttpServlet {

    private static final String COOKIE_NAME = "userInfo";

    TbUserService tbUserService = new TbUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userInfo = CookieUtils.getCookieValue(req, COOKIE_NAME);
        if(StringUtils.isNotBlank(userInfo)){
            //        String[] split = userInfo.split(":");
            String[] split = StringUtils.split(userInfo, ":");
            req.setAttribute("email",split[0]);
            req.setAttribute("passWord",split[1]);
            req.setAttribute("rememberMe","checked");
        }
        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String passWord = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");
        TbUser tbUser = tbUserService.selectByEmail(email);
        if(!"on".equals(rememberMe)){
            CookieUtils.deleteCookie(req,resp,COOKIE_NAME);
        }
        if (tbUser != null) {
            if (tbUser.getPassWord().equals(DigestUtils.md5Hex(passWord))) {
                if (StringUtils.isNotBlank(rememberMe) && "on".equals(rememberMe)) {
                    CookieUtils.setCookie(req, resp, COOKIE_NAME, String.format("%s:%s",email,passWord), 60 * 60 * 24 * 7);
                }
                req.getSession().setAttribute("sessionInfo",tbUser);
                resp.sendRedirect("main.jsp");
            } else {
                req.setAttribute("message", "密码错误，请重新登录");
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        } else {
            req.setAttribute("message", "账户不存在，请重新登录");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }

    }
}
